package com.wuqi.dev;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ChildThread extends Thread{

    public static final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    @Override
    public void run() {
        try {
            while (true){
                Runnable take = queue.take();
                take.run();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void add(Runnable r){
        queue.add(r);
    }

    public void test(){
        System.out.println(queue.size());
    }

    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool();
        pool.start();
        for (int i = 0; i < 10; i++) {
            final int index = i + 1;
            pool.run(() -> {
                System.out.println("线程" + index);
                sleep(1000);
            });
        }


    }

    private static void sleep(int time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadPool{
    private ChildThread[] threads = new ChildThread[3];

    public ThreadPool() {
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new ChildThread();
        }
    }

    public void start(){
        for (ChildThread thread : threads) {
            thread.start();
        }
    }

    public void run(Runnable r){
        ChildThread.queue.add(r);
    }

}
